<template>
    <div>
        <header-title>
            <template #title>{{ type == 'add' ? '新增' : '编辑' }}业务类型</template>
            <template #btn>
                <el-button type="primary" @click="onSubmit()">保 存</el-button>
                <el-button @click="closeForm">关 闭</el-button>
            </template>
        </header-title>
        <div class="search-box">
            <el-form ref="dataFormRef" :model="form" :inline="true" :rules="rules" class="demo-form-inline"
                label-position="top">

                <el-form-item prop="typeName" label="业务类型名称">
                    <el-input v-model="form.typeName" clearable placeholder="请输入业务类型名称" />
                </el-form-item>

                <el-form-item prop="typeCode" label="务类型code">
                    <el-input v-model="form.typeCode" clearable :disabled="type !== 'add'" placeholder="请输入业务类型code" />
                </el-form-item>
                <el-form-item prop="tags" label="业务性质">
                    <el-select v-model="form.tags" placeholder="请选择业务性质" class="width-parent" clearable multiple>
                        <el-option v-for="item in bizTypeQualityList" :key="item.code" :value="item.code"
                            :label="item.name" />
                    </el-select>
                </el-form-item>

                <el-form-item class="seting-box">
                    <el-button type="primary" @click="settingIcon" :icon="EditPen">设置业务类型图标
                    </el-button>
                    <img v-show="form.iconUrl" :src="form.iconUrl"
                        style="width:32px;height:32px;margin-left:10px;botder: 1px solid #dddddd;" />
                </el-form-item>

            </el-form>
        </div>
        <div class="main-box">
            <div class="btn-box">
                <el-button type="primary" @click="showAddFrom">新增字段</el-button>
                <el-button :disabled="selectItem.length == 0" @click="deleteRow()">删除</el-button>
                <el-button :disabled="selectItem.length == 0" @click="editItem('off')">停用</el-button>
                <el-button :disabled="selectItem.length == 0" @click="editItem('on')">启用</el-button>
            </div>
            <PubilcTable :isSlot="false" :table-data="tableData" :list-config="columns" :showSelect="true" :showPageSize="false"
                :page-data="pageData" @on-action="onAction" @on-selectChange="changeSelectItem" />
        </div>
        <eForm :dialog-visible="dialogVisible" :is-add="isAdd" :formData="formData" @on-submit="formSubmit"
            @handle-close="handleClose" />
        <iconForm :dialog-visible="dialogVisible2" @on-submit="iconSubmit" @handle-close="handleClose" />
    </div>
</template>
<script  setup>
import { reactive, ref } from 'vue'
import { PREFIX } from '@/constant/const'
import eForm from '../components/addDataForm.vue'
import iconForm from '../components/settingIconForm.vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import api from '@/api/index'
import { EditPen } from '@element-plus/icons-vue'

let router = useRouter();
const route = useRoute();
const dataFormRef = ref(null)
const form = ref({ tags: [] })
const selectItem = ref([])
const dialogVisible = ref(false)
const dialogVisible2 = ref(false)
const isAdd = ref('add')
const pageData = reactive({
    pageNum: 1,
    pageSize: 10,
    total: 0
})

const bizTypeQualityList = ref([])//业务性质


const formData = ref({})
const editIndex = ref(null)
const type = ref('add')
const options = ref({})
const imgIconUrl = ref('')

const validatetypeCode = (rule, value, callback) => {
    let reg = /^[a-zA-Z]\w+$/
    let status = true
    const arr = PREFIX.validateLisOptions
    arr.forEach((item) => {
        if (value === item) {
            callback(new Error('不能为关键字' + item))
            status = false
        }
    })
    if (status) {
        if (!reg.test(value)) {
            callback(new Error('26个英文字母和0-9的自然数+下划线组成，首字符为字母'))
        } else {
            callback()
        }
    }
}

const rules = reactive({
    typeName: [
        {
            required: true,
            message: '请输入业务类型名称',
            trigger: 'blur'
        }
    ],
    typeCode: [
        {
            required: true,
            message: '请输入业务类型code',
            trigger: 'blur'
        },
        { validator: validatetypeCode, trigger: 'blur' }
    ],
    tags: [
        {
            required: false,
            message: '请选择',
            trigger: 'blur'
        }
    ]
})
const tableData = ref([])
const tagsOptions = ref([])

const OPERTATE = [
    { alias: 'edit', label: '编辑' },
    { alias: 'moveUp', label: '上移' },
    { alias: 'moveDown', label: '下移' },
]

const columns = [
    { alias: 'fieldName', label: '字段名称' },
    { alias: 'fieldCode', label: '字段code' },
    { alias: 'fieldType', label: '字段类型' },
    { alias: 'fieldLength', label: '字段长度' },
    { alias: 'only', label: '是否唯一' },
    { alias: 'status', label: '状态', type: 'switch' },
    { label: '操作', listArr: OPERTATE, width: '150px', fixed: 'right', type: 'action' }
]

onMounted(() => {
    getBizQualityList()
    getByTypeCode()
    type.value = route.query.type
    if (type.value === 'add') {
        form.value.iconUrl = 'https://img-test.sjgo365.com/fssc-product/79012f8d-e920-49fb-a486-db8f6ac7237a-2022030103401715.png'
    } else {
        const data = localStorage.getItem('typeDetailParams');
        if (data) {
            const dataForm = { ...JSON.parse(data) }
            form.value = dataForm
            console.log(dataForm)
            form.value.typeName = form.value.typeName
            form.value.typeCode = form.value.typeCode
            form.value.tags = dataForm.tags && dataForm.tags.split(",")
            if (form.value.metaData !== 'null') {
                tableData.value = [...JSON.parse(form.value.metaData)]
                tableData.value.forEach((item) => {
                    if (item.status === 1) {
                        item.status = true
                    } else {
                        item.status = false
                    }
                })
            } else {
                tableData.value = []
            }
            pageData.total = tableData.value.length
        }
    }
})

// 获取业务性质
const getBizQualityList = () => {
    api.reimbursement.BizQualityList().then(res => {
        console.log(res)
        bizTypeQualityList.value = res
    })
}


const getByTypeCode = () => {
    const params = {
        code: 'reimburse_biz_type_tag'
    }
    api.dataMaintenance.getByTypeCode(params).then((res) => {
        tagsOptions.value = res || []
    })
}

const deleteRow = () => {
    if (selectItem.value.length > 0) {
        ElMessageBox.confirm('确定删除此枚举信息吗？删除后将不可恢复。', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            const newList = tableData.value.filter((item) => {
                let tar = true
                selectItem.value.forEach((item2) => {
                    if (item.fieldCode === item2.fieldCode) {
                        tar = false
                    }
                })
                if (tar) {
                    return item
                }
            });
            tableData.value = newList
            ElMessage({
                type: 'success',
                message: '删除成功!'
            });
        })
    } else {
        ElMessage({
            type: 'error',
            message: '请至少勾选一项数据!'
        });
    }
}
const editItem = (type) => {
    if (selectItem.value.length > 0) {
        let text = ''
        if (type === 'off') {
            text = '停用'
        } else {
            text = '启用'
        }
        ElMessageBox.confirm('确定' + text + '选中的字段吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            tableData.value.forEach((item) => {
                selectItem.value.forEach((item2) => {
                    if (item.fieldCode === item2.fieldCode) {
                        if (type === 'off') {
                            item.status = false
                        } else {
                            item.status = true
                        }
                    }
                })
            });
            ElMessage({
                type: 'success',
                message: text + '成功!'
            });
        })
    } else {
        ElMessage({
            type: 'error',
            message: '请至少勾选一项数据!'
        });
    }
}
const onAction = ([item, row, index]) => {
    const obj = {
        'del': deleteRow,
        'edit': editRow,
        'moveUp': moveUp,
        'moveDown': moveDown
    }
    if (typeof item === 'string') {
        pageData[item] = row
        if (item === 'size') pageData.page = 1
        obj[item]()
    } else {
        obj[item.alias](row, index)
    }
}
const editRow = (row, index) => {
    formData.value = row
    editIndex.value = index
    dialogVisible.value = true
    isAdd.value = 'edit'
}
const showAddFrom = () => {
    dialogVisible.value = true
    isAdd.value = 'add'
    formData.value = {
        only: false
    }
}
const formSubmit = (data, type) => {
    if (type === 'add') {
        let contiue = true
        try {
            tableData.value.forEach((item) => {
                if (data.fieldCode === item.fieldCode) {
                    ElMessage({
                        type: 'error',
                        message: '字段code与该表已有字段code不能相同!'
                    });
                    contiue = false
                    throw Error()
                }
                if (data.fieldName === item.fieldName) {
                    ElMessage({
                        type: 'error',
                        message: '字段名称不能相同!'
                    });
                    contiue = false
                    throw Error()
                }
            });
        } catch (err) {
            console.log(err)
        }
        if (contiue) {
            tableData.value = [...tableData.value, data]
        }
    } else {
        let contiue = true
        try {
            tableData.value.forEach((item, index) => {
                if (index !== editIndex.value) {
                    if (data.fieldCode === item.fieldCode) {
                        ElMessage({
                            type: 'error',
                            message: '字段code与该表已有字段code不能相同!'
                        });
                        contiue = false
                        throw Error()
                    }
                    if (data.fieldName === item.fieldName) {
                        ElMessage({
                            type: 'error',
                            message: '字段名称不能相同!'
                        });
                        contiue = false
                        throw Error()
                    }
                }
            });
        } catch (err) {
            console.log(err)
        }
        if (contiue) {
            tableData.value = (tableData.value || []).map((item, index) => {
                if (index === editIndex.value) {
                    return item = data
                } else {
                    return item
                }
            })
        }
    }
}
const iconSubmit = (val) => {
    form.value.iconUrl = val
}
const handleClose = val => {
    dialogVisible.value = val
    dialogVisible2.value = val
}
const onSubmit = () => {
    if (!dataFormRef) return
    dataFormRef.value.validate(valid => {
        if (valid) {
            if (tableData.value.length < 1) {
                ElMessage({
                    type: 'error',
                    message: '请添加字段!'
                });
                return
            }
            tableData.value.forEach((item) => {
                if (item.status === true) {
                    item.status = 1
                } else {
                    item.status = 0
                }
            })
            form.value.mateData = JSON.stringify(tableData.value)
            if (form.value) {

                const params = { ...form.value }
                params['tags'] = params['tags'] && params['tags'].join(",")

                if (type.value === 'add') {
                    api.reimbursement.createBizType(params).then((res) => {
                       
                        ElMessage({
                            type: 'success',
                            message: '保存成功!'
                        });
                        closeForm()
                    }).catch(() => {
                        tableData.value.forEach((item) => {
                            if (item.status === 1) {
                                item.status = true
                            } else {
                                item.status = true
                            }
                        })
                    })
                } else {
                    api.reimbursement.updateBizType(params).then((res) => {
                        console.log(res, 'ressss')
                        ElMessage({
                            type: 'success',
                            message: '修改成功!'
                        });
                        closeForm()
                    }).catch(() => {
                        tableData.value.forEach((item) => {
                            if (item.status === 1) {
                                item.status = true
                            } else {
                                item.status = true
                            }
                        })
                    })
                }
            }
        } else {

            console.log('验证未通过')
        }
    })
}
const resetForm = () => {
    console.log(22222)
}
const moveUp = (row, index) => {
    if (index > 0) {
        tableData.value[index] = tableData.value.splice(index - 1, 1, tableData.value[index])[0]
    }
}
const moveDown = (row, index) => {
    if (index < tableData.value.length - 1) {
        tableData.value[index] = tableData.value.splice(index + 1, 1, tableData.value[index])[0]
    }
}
const settingIcon = () => {
    dialogVisible2.value = true
}
const changeSelectItem = (data) => {
    selectItem.value = data
}
const closeForm = () => {
    localStorage.removeItem('typeDetailParams');
    router.push({
        name: 'businessType'
    })
}
</script>

<style lang="scss" scoped>

.search-box {
    padding: 15px 20px;
    background: #fff;
    border-bottom: 1px solid #D9D9D9;
}
.main-box {
    background: #fff;
    padding:20px;
    .btn-box {
        margin-bottom: 20px;
    }
}
</style>
<style lang="scss">

.seting-box {
    .el-form-item__content {
        margin-top: 30px;
    }
}
</style>
